package logics

import (
	"context"
	"encoding/json"
	_const "git.900sui.cn/kc/apiPay/lang/const"
	"git.900sui.cn/kc/base/common/functions"
	"git.900sui.cn/kc/base/utils"
	pay2 "git.900sui.cn/kc/rpcinterface/client/pay"
	"git.900sui.cn/kc/rpcinterface/interface/pay"
	"log"
)

//微信公众号处理
type WxpayLogic struct{}

//微信需要返回对应的code 和 opencode
//如果没有code 也没用 appid 则需要推出 字符失败
func (this *WxpayLogic) Do(t functions.Controller, orderSnField string, cidField string) {
	order_sn := t.Ctx.GetString(orderSnField)
	cid := t.Ctx.GetString(cidField)
	utils.Logerr.Printf("order_sn: %s", order_sn)
	utils.Logerr.Printf("cid: %s", cid)
	code := t.Input.Post("code").String()
	if code == "" {
		t.Output.Error(_const.AppidCodeIsEmpty)
		return
	}
	xindaliClient := new(pay2.XindaluPay).Init()
	//获取用户的 openid
	openid, err := this.GetOpendid(xindaliClient, code, t.Ctx.Request.Context(), cid)

	log.Printf("code: %s", code)
	log.Printf("openid: %s", openid)
	if err != nil {
		t.Output.Error(_const.OpenidError, err.Error())
		return
	}
	//args 只需要传递订单号 即可  然后由Rpc处理查询出订单信息
	args := &pay.ArgsunionidOrder{
		OrderNO: order_sn,
		Openid:  openid,
		PayWay:  pay.PayWayWx,
		TraType: pay.TraTypeOffical,
		Ip:      functions.ClientIP(t.Ctx.Request),
		//Ip:  "223.167.121.135",
		Cid: cid,
	}
	reply := &pay.ReplyUniondOrder{}

	err = xindaliClient.UnionidOrder(t.Ctx.Request.Context(), args, reply)

	if err != nil {
		log.Printf("err: %s", err.Error())
		t.Output.Error(_const.RpcServerIsError, err.Error())
		return
	}
	log.Printf("data: %v", reply.Data)

	jsonByte, _ := json.Marshal(reply.Data)
	log.Printf("json: %s", string(jsonByte))
	t.Output.Success(reply.Data)
}

func (this *WxpayLogic) GetOpendid(client *pay2.XindaluPay, code string, ctx context.Context, cid string) (string, error) {
	reply := &pay.ReplyGetOpenid{}
	args := &pay.ArgsGetOpenid{
		Code: code,
		Cid:  cid,
	}
	err := client.GetOpenid(ctx, args, reply)
	if err != nil {
		return "", err
	}
	return reply.Openid, nil
}
